package com.googlecode.hypersphere.ejbJarXmlTransformer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.Visitor;
import org.dom4j.VisitorSupport;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class EjbJarXmlTransformer {

	public String transformElementName(String name) {
		StringBuffer result = new StringBuffer(name);
		int start = result.indexOf("-");
		while (start != -1) {
			result.replace(start, start + 2, result.substring(start + 1,
					start + 2).toUpperCase());
			start = result.indexOf("-");
		}
		result.insert(0, "j2ee:");
		return result.toString();
	}

	public File transformXML(File file, String path) throws DocumentException {
		SAXReader xmlReader = new SAXReader();
		Document doc = xmlReader.read(file);
		Element root = doc.getRootElement();
		root.remove(root.getNamespace());
		root.add(new Namespace("j2ee", "http://java.sun.com/xml/ns/j2ee"));
		root.setName(root.getName().substring(0, 1).toUpperCase()
				+ root.getName().substring(1) + "Type");
		Visitor visitor = new VisitorSupport() {
			public void visit(Element element) {
				element.setName(transformElementName(element.getName()));
			}
		};
		doc.accept(visitor);
		write(doc, path);
		File result = new File(path);
		System.out.println("Wrote successfully to " + result.getAbsolutePath());
		return result;
	}

	private void write(Document doc, String path) throws IllegalStateException {
		XMLWriter writer = null;
		OutputFormat outformat = OutputFormat.createPrettyPrint();
		outformat.setEncoding("UTF-8");
		try {
			writer = new XMLWriter(new FileWriter(path), outformat);
			writer.write(doc);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
